const {DBManager}=require('./DBManager.js')
const express = require('express');
const cors=require('cors');
const app = express();
const port = 8080;

let server=null;

function dbcheck(req, res, next){
  if(DBManager.isReady()){
    next();
  }else{
    res.json({title:'ERROR',content:'<p>数据库未准备</p>'});
  }
}

DBManager.initialize(function(){
  server=app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
  });
});

app.use(express.json());
app.use(dbcheck);
app.use(cors());
app.get('/articles/:id', (req, res) => {
  let id=req.params.id;
  if(DBManager.exist(id)){
    DBManager.readArticle(id,function(data){
      if(!data){
        res.json({title:'ERROR',content:`<p>${id}文章读取错误</p>`});
      }else{
        res.set('Access-Control-Allow-Origin:*');
        res.type('application/json');
        res.send(data);
      }
    });
  }else{
    res.json({title:'ERROR',content:`<p>${id}文章不存在</p>`});
  }
});

app.get('/gamelist',(request,response)=>{
  response.json(DBManager.articles);
});

app.post('/articles/:id',(requset,response)=>{
  let jsonbody=requset.body;
  let id=requset.params.id;
  if(jsonbody){
    switch(jsonbody.operator){
      case 'save':
        DBManager.saveArticleBack(id,jsonbody.title,jsonbody.content,
          (success)=>{
            response.send(success);
          });
        break;
      case 'commit':
        DBManager.commitArticle(id,jsonbody.title,jsonbody.content,
          (success)=>{
            response.send(success);
          });
        break;
    }
  }
});

process.on('SIGINT',function(){
  console.log('Express server closed.');
  DBManager.close(()=>{
    server.close(()=>{
      process.exit(0);
    })
  })
})